package com.mokee.android.database;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DataBaseHelper extends OrmLiteSqliteOpenHelper{
	private static final String tag = "DataBaseHelper";
	
	private static DataBaseHelper instance = null;
	private static final String databaseName = "ship.db";
	private static final int databaseVersion = 2;

	public DataBaseHelper(Context context) {
		super(context, databaseName, null, databaseVersion);
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource cs) {
		try {
			TableUtils.createTable(cs, UserTable.class);
		} catch (SQLException e) {
			Log.e(tag, "Can't create database:" + e.toString());
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) { }
	
	public static DataBaseHelper getInstance(){
		return instance;
	}
	public static DataBaseHelper getInstance(Context context){
		if(instance == null){
			synchronized (DataBaseHelper.class) {
				if(instance == null){
					instance = new DataBaseHelper(context);
				}
			}
		}
		return instance;
	}

	private UserRecord userRecord = null;
	public UserRecord getUserRecord(){
		if(userRecord == null){
			synchronized (UserRecord.class) {
				if(userRecord == null){
					RuntimeExceptionDao<UserTable, Integer> dao = getRuntimeExceptionDao(UserTable.class);
					userRecord = new UserRecord(dao);
				}
			}
		}
		return userRecord;
	}
}
